package com.ruihang.generalibrary.ui.barrage;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by lixueyong on 16/2/19.
 */
public class BarrageListView extends RelativeLayout {
    private Context mContext;
    private BarrageHandler mHandler = new BarrageHandler();
    private static final long BARRAGE_GAP_MIN_DURATION = 1000;//两个弹幕的最小间隔时间
    private static final long BARRAGE_GAP_MAX_DURATION = 2000;//两个弹幕的最大间隔时间


    private boolean isShowMsg = true;
    private int totalHeight = 0;
    private int lineHeight = 70;//每一行弹幕的高度
    private int lineAddHeight = 70;//每一行上升的高度
    private int totalLine = 0;//弹幕的行数
    private List<String> messageList = new ArrayList<>();


    public BarrageListView(Context context) {
        this(context, null);
    }

    public BarrageListView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BarrageListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    private void init() {
        int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());
        mHandler.sendEmptyMessageDelayed(0, duration);
    }

    public void addMessage(String message) {
        messageList.add(message);
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
    }

    private void generateItem() {
        if (messageList.size() > 0) {
            BarrageItem item = new BarrageItem();
            String tx = messageList.remove(0);
            int sz = 16;
            item.textView = new TextView(mContext);
            String txa[] = tx.split("=");
            tx = tx.replace("=", "");

            SpannableString spannableString = new SpannableString(tx);
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#CCFF9090"));
            spannableString.setSpan(colorSpan, 0, txa[0].length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            item.textView.setText(spannableString);
            item.textView.setGravity(Gravity.CENTER_VERTICAL);
            item.textView.setPadding(15, 5, 15, 5);
            item.textView.setTextSize(sz);
            item.textView.setBackground(getResources().getDrawable(R.drawable.gen_living_comment_bg));
//            item.textView.setBackgroundColor(Color.argb(100,155,155,155));
//            item.textView.setTextColor(Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            item.textView.setTextColor(Color.WHITE);
            item.textMeasuredWidth = (int) getTextWidth(item, tx, sz);
            totalHeight = getMeasuredHeight();
            totalLine = totalHeight / (2 * (lineHeight + 10));
            float rows = getTextRows(item, tx, sz);
            int r = 1;
            String cutTxt = "";
            if (rows > 1) {
                r = (int) rows;
                if (rows > r) {
                    r++;
                }
                int length = (int) (tx.length() / rows);
                for (int i = 0; i < r; i++) {
                    if (i == r - 1) {
                        cutTxt += tx.substring(i * length, tx.length());
                    } else {
                        cutTxt += tx.substring(i * length, (i + 1) * length) + "\n";
                    }
                }
            } else {
                cutTxt = tx;
            }
            spannableString = new SpannableString(cutTxt);
            colorSpan = new ForegroundColorSpan(Color.parseColor("#CCFF9090"));
            spannableString.setSpan(colorSpan, 0, txa[0].length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            item.textView.setText(spannableString);
            item.textHeight = lineHeight * r;
            item.verticalPos = totalHeight - 200;//减去的数值是距离底部高度
            showBarrageItem(item);
        }
    }

    private void showBarrageItem(final BarrageItem item) {
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        params.topMargin = item.verticalPos;
        params.leftMargin = 20;
        int childCout = this.getChildCount();
        if (childCout >= totalLine) {
            BarrageListView.this.removeView(this.getChildAt(0));
        }
        TextView view;
        if (this.getChildCount() > 0) {
            view = (TextView) this.getChildAt(this.getChildCount() - 1);
            lineAddHeight = view.getHeight() + 5;

            for (int i = 0; i < this.getChildCount(); i++) {
                view = (TextView) this.getChildAt(i);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
//            layoutParams.leftMargin = X - _xDelta;
                layoutParams.topMargin = layoutParams.topMargin - lineAddHeight;
//            layoutParams.rightMargin = -250;
                layoutParams.bottomMargin = layoutParams.bottomMargin - lineAddHeight;
                view.setLayoutParams(layoutParams);
            }
        }
        if (isShowMsg) {
            this.addView(item.textView, params);
        }
    }

    /**
     * 关闭弹幕，清空所有
     */
    public void clearAllMsg() {
        isShowMsg = false;
        BarrageListView.this.removeAllViews();
    }

    /**
     * 打开弹幕，允许显示
     */
    public void showMsg() {
        isShowMsg = true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean b = super.onInterceptTouchEvent(ev);
        JLog.e("intercept " + b);
        return b;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean b = super.onTouchEvent(event);
        JLog.e("touch  " + b);
        return b;
    }

    private TranslateAnimation generateTranslateAnim(BarrageItem item, int leftMargin) {
        TranslateAnimation anim = new TranslateAnimation(leftMargin, -item.textMeasuredWidth, 0, 0);
        anim.setDuration(item.moveSpeed);
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        anim.setFillAfter(true);
        return anim;
    }

    /**
     * 计算TextView中字符串的长度
     *
     * @param text 要计算的字符串
     * @param Size 字体大小
     * @return TextView中字符串的长度
     */
    public float getTextWidth(BarrageItem item, String text, float Size) {
        Rect bounds = new Rect();
        TextPaint paint;
        paint = item.textView.getPaint();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return bounds.width();
    }

    /**
     * 计算文字显示需要的行数
     *
     * @param item
     * @param text
     * @param Size
     * @return
     */
    public float getTextRows(BarrageItem item, String text, float Size) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int sreenHeight = dm.heightPixels;
        int sreenWidth = dm.widthPixels;
        Rect bounds = new Rect();
        TextPaint paint;
        paint = item.textView.getPaint();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int width = 0;
//        int sreenWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        if (sreenWidth > sreenHeight) {
            width = sreenWidth / 2;
        } else {
            width = sreenWidth * 3 / 4;
        }
        float row = (float) bounds.width() / (float) width;
        return row;
    }

    class BarrageHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            generateItem();
            //每个弹幕产生的间隔时间随机
            int duration = (int) ((BARRAGE_GAP_MAX_DURATION - BARRAGE_GAP_MIN_DURATION) * Math.random());
            this.sendEmptyMessageDelayed(0, duration);
        }
    }

}